package com.liuyang.ecommerce.advice;

import com.liuyang.ecommerce.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 * 不让客户端抛出异常。让客户端处理统一响应，统一拦截
 */
@Slf4j
@RestControllerAdvice // 捕获
public class GlobalExceptionAdvice{

    @ExceptionHandler(value = Exception.class) // 捕获的异常
    /**
     * 拦截之后通过这个方法进行返回
     */
    public CommonResponse<String> handlerCommerceException(HttpServletRequest req, Exception ex) {
        CommonResponse<String> resp = new CommonResponse<>(-1,"business error");
        resp.setData(ex.getMessage());
        log.error("commerce service has error : [{}]",ex.getMessage(),ex);
        return resp;
    }
}
